{
  "cells": [
    {
      "cell_type": "raw",
      "id": "1957f5cb",
      "metadata": {
        "vscode": {
          "languageId": "raw"
        }
      },
      "source": [
        "---\n",
        "sidebar_label: Azion EdgeSQL\n",
        "---"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "ef1f0986",
      "metadata": {},
      "source": [
        "# AzionVectorStore\n",
        "\n",
        "The `AzionVectorStore` is used to manage and search through a collection of documents using vector embeddings, directly on Azion's Edge Plataform using Edge SQL. \n",
        "\n",
        "This guide provides a quick overview for getting started with Azion EdgeSQL [vector stores](/docs/concepts/#vectorstores). For detailed documentation of all `AzionVectorStore` features and configurations head to the [API reference](https://api.js.langchain.com/classes/_langchain_community.vectorstores_azion_edgesql.AzionVectorStore.html)."
      ]
    },
    {
      "cell_type": "markdown",
      "id": "c824838d",
      "metadata": {},
      "source": [
        "## Overview\n",
        "\n",
        "### Integration details\n",
        "\n",
        "| Class | Package | [PY support] |  Package latest |\n",
        "| :--- | :--- | :---: | :---: |\n",
        "| [`AzionVectorStore`](https://api.js.langchain.com/classes/langchain_community_vectorstores_azion_edgesql.AzionVectorStore.html) | [`@langchain/community`](https://npmjs.com/@langchain/community) | ❌ |  ![NPM - Version](https://img.shields.io/npm/v/@langchain/community?style=flat-square&label=%20&) |"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "36fdc060",
      "metadata": {},
      "source": [
        "## Setup\n",
        "\n",
        "To use the `AzionVectorStore` vector store, you will need to install the `@langchain/community` package. Besides that, you will need an [Azion account](https://www.azion.com/en/documentation/products/accounts/creating-account/) and a [Token](https://www.azion.com/en/documentation/products/guides/personal-tokens/) to use the Azion API, configuring it as environment variable `AZION_TOKEN`. Further information about this can be found in the [Documentation](https://www.azion.com/en/documentation/).\n",
        "\n",
        "This guide will also use [OpenAI embeddings](/docs/integrations/text_embedding/openai), which require you to install the `@langchain/openai` integration package. You can also use [other supported embeddings models](/docs/integrations/text_embedding) if you wish.\n",
        "\n",
        "```{=mdx}\n",
        "import IntegrationInstallTooltip from \"@mdx_components/integration_install_tooltip.mdx\";\n",
        "import Npm2Yarn from \"@theme/Npm2Yarn\";\n",
        "\n",
        "<IntegrationInstallTooltip></IntegrationInstallTooltip>\n",
        "\n",
        "<Npm2Yarn>\n",
        "  azion @langchain/openai @langchain/community\n",
        "</Npm2Yarn>\n",
        "```\n",
        "\n",
        "### Credentials\n",
        "\n",
        "Once you've done this set the AZION_TOKEN environment variable:\n",
        "\n",
        "```typescript\n",
        "process.env.AZION_TOKEN = \"your-api-key\"\n",
        "```\n",
        "\n",
        "If you are using OpenAI embeddings for this guide, you'll need to set your OpenAI key as well:\n",
        "\n",
        "```typescript\n",
        "process.env.OPENAI_API_KEY = \"YOUR_API_KEY\";\n",
        "```\n",
        "\n",
        "If you want to get automated tracing of your model calls you can also set your [LangSmith](https://docs.smith.langchain.com/) API key by uncommenting below:\n",
        "\n",
        "```typescript\n",
        "// process.env.LANGCHAIN_TRACING_V2=\"true\"\n",
        "// process.env.LANGCHAIN_API_KEY=\"your-api-key\"\n",
        "```"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "93df377e",
      "metadata": {},
      "source": [
        "## Instantiation"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 64,
      "id": "dc37144c-208d-4ab3-9f3a-0407a69fe052",
      "metadata": {
        "tags": []
      },
      "outputs": [],
      "source": [
        "import { AzionVectorStore } from \"@langchain/community/vectorstores/azion_edgesql\";\n",
        "import { OpenAIEmbeddings } from \"@langchain/openai\";\n",
        "\n",
        "const embeddings = new OpenAIEmbeddings({\n",
        "  model: \"text-embedding-3-small\",\n",
        "});\n",
        "\n",
        "// Instantiate with the constructor if the database and table have already been created\n",
        "const vectorStore = new AzionVectorStore(embeddings, { dbName: \"langchain\", tableName: \"documents\" });\n",
        "\n",
        "// If you have not created the database and table yet, you can do so with the setupDatabase method\n",
        "// await vectorStore.setupDatabase({ columns:[\"topic\",\"language\"], mode: \"hybrid\" })\n",
        "\n",
        "// OR instantiate with the static method if the database and table have not been created yet\n",
        "// const vectorStore = await AzionVectorStore.initialize(embeddingModel, { dbName: \"langchain\", tableName: \"documents\" }, { columns:[], mode: \"hybrid\" })"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "ac6071d4",
      "metadata": {},
      "source": [
        "## Manage vector store\n",
        "\n",
        "### Add items to vector store"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 52,
      "id": "17f5efc0",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Inserting chunks\n",
            "Inserting chunk 0\n",
            "Chunks inserted!\n"
          ]
        }
      ],
      "source": [
        "import type { Document } from \"@langchain/core/documents\";\n",
        "\n",
        "const document1: Document = {\n",
        "  pageContent: \"The powerhouse of the cell is the mitochondria\",\n",
        "  metadata: { language: \"en\", topic: \"biology\" }\n",
        "};\n",
        "\n",
        "const document2: Document = {\n",
        "  pageContent: \"Buildings are made out of brick\",\n",
        "  metadata: { language: \"en\", topic: \"history\" }\n",
        "};\n",
        "\n",
        "const document3: Document = {\n",
        "  pageContent: \"Mitochondria are made out of lipids\",\n",
        "  metadata: { language: \"en\", topic: \"biology\" }\n",
        "};\n",
        "\n",
        "const document4: Document = {\n",
        "  pageContent: \"The 2024 Olympics are in Paris\",\n",
        "  metadata: { language: \"en\", topic: \"history\" }\n",
        "}\n",
        "\n",
        "const documents = [document1, document2, document3, document4];\n",
        "\n",
        "await vectorStore.addDocuments(documents);"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "dcf1b905",
      "metadata": {},
      "source": [
        "### Delete items from vector store"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 53,
      "id": "ef61e188",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Deleted 1 items from documents\n"
          ]
        }
      ],
      "source": [
        "await vectorStore.delete([\"4\"]);"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "c3620501",
      "metadata": {},
      "source": [
        "## Query vector store\n",
        "\n",
        "Once your vector store has been created and the relevant documents have been added you will most likely wish to query it during the running of your chain or agent. \n",
        "\n",
        "### Query directly\n",
        "\n",
        "Performing a simple similarity search can be done as follows:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 66,
      "id": "aa0a16fa",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Hybrid Search Results\n",
            "[{\"pageContent\":\"The Australian dingo is a unique species that plays a key role in the ecosystem\",\"metadata\":{\"searchtype\":\"fulltextsearch\"},\"id\":\"6\"},-0.25748711028997995]\n",
            "[{\"pageContent\":\"The powerhouse of the cell is the mitochondria\",\"metadata\":{\"searchtype\":\"fulltextsearch\"},\"id\":\"16\"},-0.31697985337654005]\n",
            "[{\"pageContent\":\"Australia s indigenous people have inhabited the continent for over 65,000 years\",\"metadata\":{\"searchtype\":\"similarity\"},\"id\":\"3\"},0.14822345972061157]\n"
          ]
        }
      ],
      "source": [
        "const filter = [{ operator: \"=\", column: \"language\", value: \"en\" }]\n",
        "\n",
        "const hybridSearchResults = await vectorStore.azionHybridSearch(\"biology\", {kfts:2, kvector:1, \n",
        "                                      filter:[{ operator: \"=\", column: \"language\", value: \"en\" }]});\n",
        "\n",
        "console.log(\"Hybrid Search Results\")\n",
        "for (const doc of hybridSearchResults) {\n",
        "  console.log(`${JSON.stringify(doc)}`);\n",
        "}"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 67,
      "id": "5efd2eaa",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Similarity Search Results\n",
            "[{\"pageContent\":\"Australia s indigenous people have inhabited the continent for over 65,000 years\",\"metadata\":{\"searchtype\":\"similarity\"},\"id\":\"3\"},0.4486490488052368]\n"
          ]
        }
      ],
      "source": [
        "const similaritySearchResults = await vectorStore.azionSimilaritySearch(\"australia\", {kvector:3, filter:[{ operator: \"=\", column: \"topic\", value: \"history\" }]});\n",
        "\n",
        "console.log(\"Similarity Search Results\")\n",
        "for (const doc of similaritySearchResults) {\n",
        "  console.log(`${JSON.stringify(doc)}`);\n",
        "}"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "0c235cdc",
      "metadata": {},
      "source": [
        "### Query by turning into retriever\n",
        "\n",
        "You can also transform the vector store into a [retriever](/docs/concepts/#retrievers) for easier usage in your chains. "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 56,
      "id": "f3460093",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[\n",
            "  Document {\n",
            "    pageContent: 'Australia s indigenous people have inhabited the continent for over 65,000 years',\n",
            "    metadata: { searchtype: 'similarity' },\n",
            "    id: '3'\n",
            "  },\n",
            "  Document {\n",
            "    pageContent: 'Mitochondria are made out of lipids',\n",
            "    metadata: { searchtype: 'similarity' },\n",
            "    id: '18'\n",
            "  }\n",
            "]\n"
          ]
        }
      ],
      "source": [
        "const retriever = vectorStore.asRetriever({\n",
        "  // Optional filter\n",
        "  filter: filter,\n",
        "  k: 2,\n",
        "});\n",
        "await retriever.invoke(\"biology\");"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e2e0a211",
      "metadata": {},
      "source": [
        "### Usage for retrieval-augmented generation\n",
        "\n",
        "For guides on how to use this vector store for retrieval-augmented generation (RAG), see the following sections:\n",
        "\n",
        "- [Tutorials: working with external knowledge](/docs/tutorials/#working-with-external-knowledge).\n",
        "- [How-to: Question and answer with RAG](/docs/how_to/#qa-with-rag)\n",
        "- [Retrieval conceptual docs](/docs/concepts/retrieval)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "8a27244f",
      "metadata": {},
      "source": [
        "## API reference\n",
        "\n",
        "For detailed documentation of all AzionVectorStore features and configurations head to the [API reference](https://api.js.langchain.com/classes/_langchain_community.vectorstores_azion_edgesql.AzionVectorStore.html)."
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "TypeScript",
      "language": "typescript",
      "name": "tslab"
    },
    "language_info": {
      "codemirror_mode": {
        "mode": "typescript",
        "name": "javascript",
        "typescript": true
      },
      "file_extension": ".ts",
      "mimetype": "text/typescript",
      "name": "typescript",
      "version": "3.7.2"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
